package fc;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import fc.entity.OaEntity;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.upgradetool.wscheck.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ZH_CREATE_CUST implements Action{

	@Override
	public String execute(RequestInfo info) {
		String API_NAME="ZH_CREATE_CUST";

		BaseBean log = new BaseBean();

		log.writeLog("接口"+API_NAME+"开始调用-----------------------------------");

		OaEntity oa=new OaEntity();

		String requestid = info.getRequestid();
		String tablename = info.getRequestManager().getBillTableName();
		oa.setREQUESTID(requestid);

		String sql=
		"select  id,REQUESTID,jydxjc JIANCHENG   ,jydxqm QUANCHENG  ,gyjybz CUR_ID ,gyjysz TAX_NO,gyjytj JYTJ,gyfktj FKTJ,"+
		"jdrbh USERID  ,gzbmbh DEPARTMENTID  ,cgybh CG_USERID , ZKLB ,sh SHUIHAO  ,gysbm CUS_NO  ,GJDQ ,ENT," +
		"case when gysxz in ('0','2') then  '1' else '2' end  CUS_TYPE,gyqjfs QJFS,gyfplx FPLX," +
		"case  gysxz  when '0' then '10' when '1' then '10' when '2' then '50' else '' end  TYPENO   "+
		"from "+tablename+"   WHERE REQUESTID="+requestid;

		//


        RecordSet rs = new RecordSet();
        rs.executeSql(sql);
        if(rs.next()){
			oa.setREQUESTID(Util.null2String(rs.getString("REQUESTID")));
			oa.setJIANCHENG(Util.null2String(rs.getString("JIANCHENG")));
			oa.setQUANCHENG(Util.null2String(rs.getString("QUANCHENG")));
			oa.setCUR_ID(Util.null2String(rs.getString("CUR_ID")));
			oa.setTAX_NO(Util.null2String(rs.getString("TAX_NO")));
			oa.setJYTJ(Util.null2String(rs.getString("JYTJ")));
			oa.setFKTJ(Util.null2String(rs.getString("FKTJ")));
			oa.setUSERID(Util.null2String(rs.getString("USERID")));
			oa.setSHUIHAO(Util.null2String(rs.getString("SHUIHAO")));
			oa.setZKLB(Util.null2String(rs.getString("ZKLB")));
			oa.setCG_USERID(Util.null2String(rs.getString("CG_USERID")));
			oa.setDEPARTMENTID(Util.null2String(rs.getString("DEPARTMENTID")));
			oa.setCUS_NO(Util.null2String(rs.getString("CUS_NO")));
			oa.setGJDQ(Util.null2String(rs.getString("GJDQ")));
			oa.setENT(Util.null2String(rs.getString("ENT")));

			oa.setCUS_TYPE(Util.null2String(rs.getString("CUS_TYPE")));
			oa.setTYPENO(Util.null2String(rs.getString("TYPENO")));

			oa.setQJFS(Util.null2String(rs.getString("QJFS")));
			oa.setFPLX(Util.null2String(rs.getString("FPLX")));




		}



		String sql1="select id,mainid,jybh JYBH  ,gjdq  GJDQ,dz DIZHI,CASE WHEN zydz='1' THEN 'Y' ELSE 'N' END  SFZY from  "+tablename+"_dt1 where mainid =(select id from "+tablename+" where requestid="+requestid+")";

        RecordSet rs1 = new RecordSet();
        rs1.executeSql(sql1);
        while(rs1.next()){
            List<OaEntity> dts=oa.getDT1();
            OaEntity dt1=new OaEntity();
            dt1.setJYBH(Util.null2String(rs1.getString("JYBH")));
            dt1.setGJDQ(Util.null2String(rs1.getString("GJDQ")));
            dt1.setDIZHI(Util.null2String(rs1.getString("DIZHI")));
            dt1.setSFZY(Util.null2String(rs1.getString("SFZY")));
			dts.add(dt1);
            oa.setDT1(dts);
        }

		String sql2="select id,mainid, TXLX    ,TXNR ,CASE WHEN zylxfs ='1' THEN 'Y' ELSE 'N' END  SFZY  from  "+tablename+"_dt2 where mainid =(select id from "+tablename+" where requestid="+requestid+")";
		RecordSet rs2 = new RecordSet();
		rs2.executeSql(sql2);
		while(rs2.next()){
			List<OaEntity> dts=oa.getDT2();
			OaEntity dt2=new OaEntity();
			dt2.setTXLX(Util.null2String(rs2.getString("TXLX")));
			dt2.setTXNR(Util.null2String(rs2.getString("TXNR")));
			dt2.setSFZY(Util.null2String(rs2.getString("SFZY")));
			dts.add(dt2);
			oa.setDT2(dts);
		}

		String sql3="select id,mainid,yxbh YHBH   ,yxzh YHZH ,CASE WHEN ZYSKZH='1' THEN 'Y' ELSE 'N' END SFZY1, CASE WHEN ZYFKZH='1' THEN 'Y' ELSE 'N' END SFZY2,zhmc  ZHMC   from  "+tablename+"_dt3  " +
				"where mainid =(select id from "+tablename+" where requestid="+requestid+")";
		RecordSet rs3 = new RecordSet();
		rs3.executeSql(sql3);
		while(rs3.next()){
			List<OaEntity> dts=oa.getDT3();
			OaEntity dt3=new OaEntity();
			dt3.setYHBH(Util.null2String(rs3.getString("YHBH")));
			dt3.setYHZH(Util.null2String(rs3.getString("YHZH")));
			dt3.setSFZY1(Util.null2String(rs3.getString("SFZY1")));
			dt3.setSFZY2(Util.null2String(rs3.getString("SFZY2")));
			dt3.setZHMC(Util.null2String(rs3.getString("ZHMC")));

			dts.add(dt3);
			oa.setDT3(dts);
		}


		String sql4="select id,mainid,jytjbh JYTJ, CASE WHEN zyjytj ='1' THEN 'Y' ELSE 'N' END SFZY      from  "+tablename+"_dt4  where mainid =(select id from "+tablename+" where requestid="+requestid+")";
		RecordSet rs4 = new RecordSet();
		rs4.executeSql(sql4);
		while(rs4.next()){
			List<OaEntity> dts=oa.getDT4();
			OaEntity dt4=new OaEntity();
			dt4.setJYTJ(Util.null2String(rs4.getString("JYTJ")));
			dt4.setSFZY(Util.null2String(rs4.getString("SFZY")));
			dts.add(dt4);
			oa.setDT4(dts);
		}


		String testparam="";
		log.writeLog("接口"+API_NAME+"参数开始-----------------------------------"+oa.getREQUESTID());

		log.writeLog("main-----------------------------------");
		log.writeLog("REQUESTID :"+oa.getREQUESTID());
		testparam="";
		log.writeLog("dt1-----------------------------------");

		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String  timestamp= format.format(new Date());
		DateFormat formataa = new SimpleDateFormat("yyyy-MM-dd");
		String createdate = formataa.format(new Date());


		String json_param=
				"{"+
						"\"key\": \"a5e7f741701e726aefeaaa58199a724f\","+
						"\"type\": \"sync\","+
						"\"host\": {"+
						"\"prod\": \"OAPI\","+
						"\"ip\": \"10.10.10.1\","+
						"\"lang\": \"zh_CN\","+
						"\"timestamp\": \""+timestamp+"\","+
						"\"acct\": \"tiptop\""+
						"},"+
						"\"service\": {"+
						"\"prod\": \"T100\","+
						"\"name\": \"supplier_crt\","+
						"\"ip\": \"10.10.10.75\","+
						"\"id\": \"topprod\""+
						"},"+
						"\"datakey\": {"+
						"\"EntId\": \""+oa.getENT()+"\","+   //--2代表正式区， 23代表测试区
						"\"CompanyId\": \"ZH00\","+
						"\"supplier_no\": \""+oa.getCUS_NO()+"\""+  //--供应商完整编码
						"},"+
						"\"payload\": {"+
						"\"std_data\": {"+
						"\"parameter\": {"+
						"\"enterprise_no\": \""+oa.getENT()+"\", "+  //--正式区，测试区这里填23
						"\"site_no\": \"ZH00\","+     //--据点，ZH00代表珠海迈为
						"\"is_digiwin_product\": \"Y\","+
						"\"supplier_detail\": ["+
						"{"+
						"\"tp\": \""+oa.getTYPENO()+"\","+   //--供应商类别
						"\"supplier_no\": \""+oa.getCUS_NO()+"\","+   //--供应商完整编码，不要重复
						"\"supplier_full_name\": \""+oa.getQUANCHENG()+"\","+   //--不要重复
						"\"supplier_shortname\": \""+oa.getJIANCHENG()+"\","+  //--不要重复
						"\"trans_object_type\": \"1\","+
						"\"if_temp\": \""+oa.getCUS_TYPE()+"\","+  //是否是临时的，1代表正式，2代表临时的，可用90天

						"\"legal_type\": \"1\","+
						"\"belong_legal\": \""+oa.getCUS_NO()+"\","+   //--完整供应商编码
						"\"belong_group_no\": \"\","+
						"\"uniform_number\": \""+oa.getSHUIHAO()+"\","+    //--税号，不可重复
						"\"country_no\": \""+oa.getGJDQ()+"\","+ // 国家地区
						"\"industry_id\": \"\","+
						"\"monthly_settlement_day\": \"1\","+
						"\"payment_day\": \"1\","+
						"\"receivable_day\": \"1\","+
						"\"purchaser_no\": \""+oa.getUSERID()+"\","+   //--采购员编号
						"\"responsibility_department_no\": \""+oa.getDEPARTMENTID()+"\","+     //--归属部门编号
						"\"create_employee_no\": \""+oa.getUSERID()+"\","+   //--建档人的编号
						"\"currency_no\": \""+oa.getCUR_ID()+"\","+   //--币种
						"\"tax_no\": \""+oa.getTAX_NO()+"\", "+  //--税种
						"\"payment_condition_no\": \""+oa.getFKTJ()+"\","+   //--付款条件
						"\"trade_condition_no\": \""+oa.getJYTJ()+"\","+     //--交易条件
						"\"account_type\": \""+oa.getZKLB()+"\","+  //--帐款类别
						"\"get_prc_way\": \""+oa.getQJFS()+"\","+  //---取价方式
						"\"invoice_type\": \""+oa.getFPLX()+"\","+  //--发票类型

						"\"create_date\": \""+createdate+"\","+
						"\"trans_object_relation_detail\": ["+
						"{"+
						"\"trade_type\": \"1\","+  //--1代表收付款对象类型
						"\"is_main\": \"Y\","+
						"\"trans_object_no\": \""+oa.getCUS_NO()+"\""+   //--完整供应商编号
						"}"+
						"],"+
						"\"contact_address_detail\": [";

		testparam="";
		for(int i=0;i<oa.getDT1().size();i++){

			if (!"".equals(testparam)){
				testparam=testparam+",";
			}
			testparam+=
					//地址的
					"{"+
							"\"brief_no\": \""+oa.getDT1().get(i).getJYBH()+"\","+
							"\"address_type\": \"1\","+   //--1代表登记地址
							"\"is_main_contact_address\": \""+oa.getDT1().get(i).getSFZY()+"\","+
							"\"country_code\": \""+oa.getDT1().get(i).getGJDQ()+"\","+
							"\"address\": \""+oa.getDT1().get(i).getDIZHI()+"\","+  //--地址信息
							"\"expiration_date\": \"9999-01-01\""+
							"}";
			//地址的
		}
		json_param+=testparam;


		json_param+=
				"],"+
						"\"communication_detail\": [";



		testparam="";
		for(int i=0;i<oa.getDT2().size();i++){

			if (!"".equals(testparam)){
				testparam=testparam+",";
			}
			testparam+=
					//联系方式
					"{"+
							"\"communication_type\": \""+oa.getDT2().get(i).getTXLX()+"\","+
							"\"communication_content\": \""+oa.getDT2().get(i).getTXNR()+"\","+  //--电话号码
							"\"is_main_communication_method\": \""+oa.getDT2().get(i).getSFZY()+"\","+
							"\"expiration_date\": \"9999-01-01\""+
							"}";
			//联系方式
		}
		json_param+=testparam;



		json_param+=
				"],"+
						"\"bank_info\": [";

		testparam="";
		for(int i=0;i<oa.getDT3().size();i++){

			if (!"".equals(testparam)){
				testparam=testparam+",";
			}
			testparam+=
					//银行信息
					"{"+
							"\"bank_code\": \""+oa.getDT3().get(i).getYHBH()+"\","+  //--银行编号
							"\"bank_account\": \""+oa.getDT3().get(i).getYHZH()+"\","+  //--银行帐号
							"\"main_receive_bank_account\": \""+oa.getDT3().get(i).getSFZY1()+"\","+
							"\"main_payment_bank_account\": \""+oa.getDT3().get(i).getSFZY2()+"\","+
							"\"owner_name\": \""+oa.getDT3().get(i).getZHMC()+"\""+



							"}";
			//银行信息
		}
		json_param+=testparam;

		json_param+=
				"],"+
						"\"allow_payment_condition\": [";


		json_param+=


				testparam="";
		for(int i=0;i<oa.getDT4().size();i++){

			if (!"".equals(testparam)){
				testparam=testparam+",";
			}
			testparam+=
					//付款条件
					"{"+
							"\"trade_condition_no\": \""+oa.getDT4().get(i).getJYTJ()+"\", "+  //--充许付款条件编号
							"\"is_main\": \""+oa.getDT4().get(i).getSFZY()+"\""+
							"}";
			//付款条件
		}
		json_param+=testparam;



		json_param+=
				"]"+
						"}"+
						"]"+
						"}"+
						"}"+
						"}"+
						"}";


		log.writeLog("接口"+API_NAME+"json_param:"+json_param);
		log.writeLog("接口"+API_NAME+"json_param:");

		String mmmm=json_param;
		int start=0;
		for(int ii=0;ii<mmmm.length();ii++){
			if(ii%800==0&&ii!=0){
				log.writeLog(mmmm.substring(start,ii));
				start=ii;
			}
		}
		if(start!=mmmm.length()){
			log.writeLog(mmmm.substring(start,mmmm.length()));
		}


//调用 ECOLOGY 系统接口
		String data = HttpRequest.post(FcHttpCon.ZH_YFSY_XQ).body(json_param).execute().body();
		System.out.println(data);
		String result="ERROR";
		System.out.println("----------------");

		try {

			Object succesResponse = JSON.parse(data);
			Map map = (Map)succesResponse;
			Map map1 = (Map)map.get("payload");
			Map map2 = (Map)map1.get("std_data");
			Map map3 = (Map)map2.get("execution");
			if("0".equals(map3.get("code"))){
				result="SUCCESS";
			}else{
				Map map4 = (Map)map2.get("parameter");

				System.out.println(map4);

				JSONArray jsonArray = new JSONArray(map4.get("supplier_no"));
				System.out.println(jsonArray);
				for( int i=0;i<jsonArray.size();i++){
					JSONObject infog = new JSONObject((Map<String, Object>) jsonArray.get(i));
					Map mapg = (Map) infog;
					result= mapg.get("execute_description").toString();//1
				}

			}

			// System.out.println(map1);
		} catch (Exception e) {
		}

		if("SUCCESS".equals(result)){
			//记录数据
			RecordSet rsg = new RecordSet();
			String sqlg="INSERT INTO FC_API_DIAOYONG_JILU VALUES('"+API_NAME+"',"+requestid+",GETDATE())";
			rsg.executeSql(sqlg);
		}else if("NOTNEED".equals(result)){
		}else{
			if("ERROR".equals(result)) {
				info.getRequestManager().setMessagecontent("接口调用失败无法提交！请联系管理员具体查看");
			}else{
				info.getRequestManager().setMessagecontent(result);
			}
			return FAILURE_AND_CONTINUE;
		}
		return SUCCESS;


	}

	public static String sendPost(String url, String param) {

		PrintWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new StringBuilder();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("contentType", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
//			System.out.println("发送 POST 请求出现异常！" + e);
			result = new StringBuilder("{\"msg\":\"SB\",\"errCode\":\"1001\"}");
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result.toString();
	}





} 